package com.hengpeng.itfints.service.impl;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.exception.ResourceNotFoundException;
import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.constants.QueryConstants.QueryType;
import com.hengpeng.common.util.SignatureHelper;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.userInfo.MobileBingRequest;
import com.hengpeng.itfinbase.message.userInfo.RealNameAuthRequest;
import com.hengpeng.itfinbase.message.userInfo.SendEmailRequest;
import com.hengpeng.itfinbase.message.userInfo.SendSMSRequest;
import com.hengpeng.itfinbase.message.userInfo.UserInfoResponse;
import com.hengpeng.itfinbase.message.userInfo.UserSetProtectPwdRequest;
import com.hengpeng.itfinbase.message.userInfo.UserUpdatePwdRequest;
import com.hengpeng.itfinbase.persist.Account;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserInfo.UserQuestionType;
import com.hengpeng.itfinbase.persist.VerifyCode.VerifyType;
import com.hengpeng.itfints.service.BaseService;
import com.hengpeng.itfints.service.UserService;
import com.hengpeng.itfints.vo.MemberSession;

@Service
public class UserServiceImpl extends BaseService implements UserService {

    @Override
    public MemberSession refreshSessionUser(String userName) {
        if (userName == null || userName.trim().equals("")) {
            return null;
        }
        MemberSession member = new MemberSession();
        UserInfo user = getUserByUserName(userName);
        Account account = serviceFactory.getUserService().getAccountByUserId(user.getId());
        member.setUser(user);
        member.setAccount(account);
        member.setIsLogin(Boolean.TRUE);
        return member;
    }

    @Override
    public UserInfo getUserByUserName(String userName) {
        if (userName == null || userName.trim().equals("")) {
            return null;
        }
        DynamicQuery query = new DynamicQuery(UserInfo.class);
        query.eq("userName", userName);
        return serviceFactory.getPersistService().getEntity(query, UserInfo.class);
    }

    public Account getAccountByUserId(Long userId) {
        DynamicQuery query = new DynamicQuery(Account.class);
        query.eq("userId", userId);
        return serviceFactory.getPersistService().getEntity(query, Account.class);
    }

    /**
     * 实名认证
     * 
     * @param request
     */
    public UserInfoResponse realNameAuth(String userName, String realName, String cardNumber) {
        RealNameAuthRequest request = new RealNameAuthRequest();
        request.setUserName(userName);
        request.setRealName(realName);
        request.setCardNumber(cardNumber);
        request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_REALNAME_AUTH);
        return (UserInfoResponse) portFactory.remoteTrans(request);
    }

    /**
     * 修改密码
     * 
     * @param request
     */
    public UserInfoResponse updatePassword(String userName, String oldPassword, String password) {
        UserUpdatePwdRequest request = new UserUpdatePwdRequest();
        request.setUserName(userName);
        request.setOldPassword(oldPassword);
        request.setPassword(password);
        request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_UPDATE_PWD);
        return (UserInfoResponse) portFactory.remoteTrans(request);
    }

    /**
     * 找回密码 add by lugaofei 20151022
     * 
     * @param request
     */
    public UserInfoResponse backPassword(String mobile, String password) {
        UserUpdatePwdRequest request = new UserUpdatePwdRequest();
        request.setMobile(mobile);
        request.setPassword(password);
        request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_BACK_PWD);
        return (UserInfoResponse) portFactory.remoteTrans(request);
    }

    /**
     * 设置密保
     * 
     * @param request
     */
    @Override
    public UserInfoResponse doSetQuestion(String userName, String questionType, String answer) {
        UserSetProtectPwdRequest request = new UserSetProtectPwdRequest();
        request.setUserName(userName);
        request.setQuestionType(UserQuestionType.valueOf(questionType));
        request.setAnswer(answer);
        request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_SET_PROTECT_PWD);
        return (UserInfoResponse) portFactory.remoteTrans(request);
    }

    /**
     * 邮箱验证发送邮件
     * 
     * @param email
     * @param username
     * @param betcardno
     * @param storeId
     * @param url
     * @param returnUrl
     * @return
     */
    @Override
    public ResponseMessage sendMailForValid(String email, String username, String activeCode, String url,
            String successUrl, String errorUrl) {
        SendEmailRequest request = new SendEmailRequest();
        request.setUsername(username);
        request.setEmail(email);
        request.setType(VerifyType.VALIDEMAIL);
        request.setUrl(url);
        request.setUsername(username);
        // request.setReturnUrl(returnUrl);
        request.setSuccessUrl(successUrl);
        request.setErrorUrl(errorUrl);
        request.setActiveCode(activeCode);
        request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_VALID_EMAIL);
        return (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(request);
    }

    // @Override
    // public ResponseMessage sendMailForActive(String email, String username,
    // String activeCode, String url, String returnUrl) {
    // SendEmailRequest request = new SendEmailRequest();
    // request.setUsername(username);
    // request.setEmail(email);
    // request.setType(VerifyType.VALIDEMAIL);
    // request.setUrl(url);
    // request.setUsername(username);
    // request.setReturnUrl(returnUrl);
    // request.setActiveCode(activeCode);
    // request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_VALID_EMAIL);
    // return (ResponseMessage)
    // serviceFactory.getProtFactory().remoteTrans(request);
    // }

    /**
     * 邮箱验证邮件确认
     * 
     * @param username
     * @param verifyCode
     * @param email
     * @return
     */
    @Override
    public ResponseMessage doValidEmail(String username, String verifyCode, String email) {
        SendEmailRequest request = new SendEmailRequest();
        request.setUsername(username);
        request.setVerifyCode(verifyCode);
        request.setEmail(email);
        request.setType(VerifyType.VALIDEMAIL);
        request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_VALID_EMAIL_AFFIRM);
        return (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(request);
    }

    /**
     * 短信验证发送
     * 
     * @param mobile
     * @param username
     * @param content
     * @return
     */
    @Override
    public ResponseMessage sendSMSForValidMobile(String username, String mobile, String content, VerifyType type) {
        SendSMSRequest smsRequest = new SendSMSRequest();
        smsRequest.setUsername(username);
        smsRequest.setMobile(mobile);
        smsRequest.setType(type);
        smsRequest.setContent(content);
        smsRequest.setTransType(TransCodeConstants.MemberTransCode.MEMBER_VALID_MOBILE);
        return (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(smsRequest);
    }

    /**
     * <pre>
     * 验证短信
     * </pre>
     * 
     * @param request
     * @return
     */
    @Override
    public ResponseMessage doValidMobile(String username, String mobile, String code, VerifyType type) {
        SendSMSRequest request = new SendSMSRequest();
        request.setUsername(username);
        request.setMobile(mobile);
        request.setVerifyCode(code);
        request.setType(type);
        request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_VALID_MOBILE_AFFIRM);
        return (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(request);
    }

    /**
     * 根据手机号码查询用户
     * 
     * @param mobile
     * @return
     */
    @Override
    public UserInfo getUserByMobile(String mobile) {
        DynamicQuery query = new DynamicQuery(UserInfo.class);
        query.eq("mobile", mobile);
        return serviceFactory.getPersistService().getEntity(query, UserInfo.class);
    }

    /**
     * 根据推荐码查询用户
     * 
     * @param mobile
     * @return
     */
    @Override
    public UserInfo getUserByCode(String recommendCode) {
        DynamicQuery query = new DynamicQuery(UserInfo.class);
        query.eq("recommendCode", recommendCode);
        return serviceFactory.getPersistService().getEntity(query, UserInfo.class);
    }

    @Override
    public UserInfo getUserByEmail(String email) {
        DynamicQuery query = new DynamicQuery(UserInfo.class);
        query.eq("email", email);
        return serviceFactory.getPersistService().getEntity(query, UserInfo.class);
    }

    /**
     * <pre>
     * 绑定手机号码
     * </pre>
     * 
     * @param request
     * @return
     */
    @Override
    public ResponseMessage bingMobile(String userName, String mobile) {
        MobileBingRequest request = new MobileBingRequest();
        request.setMobile(mobile);
        request.setUserName(userName);
        request.setTransType(TransCodeConstants.MemberTransCode.MEMBER_BING_MOBILE);
        return (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(request);
    }

    /**
     * 添加邮箱
     * @param userName
     * @param password
     * @param newEmail
     * @param reNewEmail
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public ServiceResult<Object> addEmail(String userName, String password, String newEmail, String reNewEmail) {
        ServiceResult<Object> sr = new ServiceResult<Object>();
        sr.setCode(Constant.TRANSACTION_RESPONSE_CODE_UNKOWN);
        sr.setIsSuccess(false);
        if (StringUtils.isEmpty(newEmail)) {
            sr.setMessage("新邮箱不可为空");
            return sr;
        }
        if (StringUtils.isEmpty(reNewEmail)) {
            sr.setMessage("新邮箱确认不可为空");
            return sr;
        }
        if (!newEmail.equals(reNewEmail)) {
            sr.setMessage("两次输入邮箱地址不一致");
            return sr;
        }
        UserInfo userinfo = this.validatePassword(userName, password);
        if (null == userinfo) {
            sr.setMessage("密码不正确");
            return sr;
        }
        userinfo.setEmail(newEmail);
        userinfo.setIsEmailCheck(BoolValue.YES);
        serviceFactory.getPersistService().update(userinfo);
        sr.setCode(Constant.TRANSACTION_RESPONSE_CODE_SUCCESS);
        sr.setIsSuccess(true);
        sr.setReturnValue(userinfo);
        return sr;

    }

    /**
     * 修改邮箱
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public ServiceResult<Object> updateEmail(String userName, String password, String email, String newEmail,
            String reNewEmail) {
        ServiceResult<Object> serviceResult = emailupdateRuleCheck(userName, password, email, newEmail, reNewEmail);
        if (!serviceResult.getIsSuccess()) {
            return serviceResult;
        } else {
            UserInfo userinfo = (UserInfo) serviceResult.getReturnValue();
            userinfo.setEmail(newEmail);
            serviceFactory.getPersistService().update(userinfo);
            return serviceResult;
        }
    }

    private ServiceResult<Object> emailupdateRuleCheck(String userName, String password, String email, String newEmail,
            String reNewEmail) {
        ServiceResult<Object> sr = new ServiceResult<Object>();
        sr.setCode(Constant.TRANSACTION_RESPONSE_CODE_UNKOWN);
        sr.setIsSuccess(false);
        if (StringUtils.isEmpty(email)) {
            sr.setMessage("旧邮箱地址不可为空");
            return sr;
        }
        if (StringUtils.isEmpty(password)) {
            sr.setMessage("密码不可为空");
            return sr;
        }
        if (StringUtils.isEmpty(newEmail)) {
            sr.setMessage("新邮箱不可为空");
            return sr;
        }
        if (StringUtils.isEmpty(newEmail)) {
            sr.setMessage("确认新邮箱不可为空");
            return sr;
        }
        if (!newEmail.equals(reNewEmail)) {
            sr.setMessage("两次邮箱输入的不一致");
            return sr;
        }
        UserInfo userinfo = this.validatePassword(userName, password);
        if (null == userinfo) {
            sr.setMessage("密码不正确");
            return sr;
        }
        if (!email.equals(userinfo.getEmail())) {
            sr.setMessage("旧邮箱不正确");
            return sr;
        }
        sr.setCode(Constant.TRANSACTION_RESPONSE_CODE_SUCCESS);
        sr.setIsSuccess(true);
        sr.setReturnValue(userinfo);
        return sr;

    }

    private UserInfo validatePassword(String userName, String passWord) {
        DynamicQuery query = new DynamicQuery(UserInfo.class);
        query.eq("username", userName);
        query.setQueryType(QueryType.JDBC);
        UserInfo userinfo = serviceFactory.getPersistService().getEntity(query, UserInfo.class);
        if (null == userinfo) {
            return null;
        }
        if (!SignatureHelper.generateMD5Signture(passWord + userinfo.getPwdAttach(), "utf-8")
                .equalsIgnoreCase(userinfo.getPassword())) {
            return null;
        } else {
            return userinfo;
        }

    }

    @Override
    public UserInfo updateRealName(Long id, String regionalType) {
        UserInfo userInfo=serviceFactory.getPersistService().get(UserInfo.class, id);
        
        if (userInfo == null)
        {
            throw new ResourceNotFoundException(id);
        }
        Date date=new Date();
        userInfo.setUpdateTime(date);
        if(regionalType!=null){
            userInfo.setRealName(regionalType+userInfo.getRealName());
        }
        return serviceFactory.getPersistService().update(userInfo);
    }

    @Override
    public UserInfo getUserById(Long id) {
        DynamicQuery query = new DynamicQuery(UserInfo.class);
        query.eq("id", id);
        return serviceFactory.getPersistService().getEntity(query, UserInfo.class);
    }
}
